#include <string>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include<unistd.h>
#include<cstdio>

#include <iostream>
#include "Comm.hpp"

const int gdefaultid = -1;
const int gsize = 4096;
const std::string pathname = ".";
const int projid = 0x66;
const int gmode = 0666; //普通文件的默认权限
#define CREATER "creater"
#define USER "user"

// 共享内存
class Shm
{
private:
    // 创建的一定要是一个全新的共享内存
    void CreaterHelper(int flag)
    {
        printf("key: 0x%x\n", _key);
        _shmid = shmget(_key, _size, flag);
        if (_shmid < 0)
        {
            ERR_EXIT("shmget");  //注意这里是类函数宏，因此if语句必须加括号防止错误
        }
         printf("shmid: %d\n", _shmid);
    }

    void Create()
    {
        CreaterHelper(IPC_CREAT | IPC_EXCL | gmode);
    }

    void Get()
    {
        CreaterHelper(IPC_CREAT);
    }
    
    void Attach()
    {
       _start_mem =  shmat(_shmid, nullptr, 0);
       if((long long)_start_mem < 0)
       {  
           ERR_EXIT("shamat");
       }
        printf("attach success\n");  
    }

    void Detach()
    {
        int n = shmdt(_start_mem);
        if(n == 0)
           printf("Dettach success!");
    }

    void Destroy()
    {
        Detach();
        if (_usertype == CREATER)
        {
            int n = shmctl(_shmid, IPC_RMID, nullptr);
            if (n > 0)
            {
                printf("shmctl delete shm: %d success!\n", _shmid);
            }
            else
            {
                ERR_EXIT("shmctl");
            }
        }
    }

public:
    Shm(const std::string &pathname, int projid, const std::string &usertype)
        : _shmid(gdefaultid), _size(projid), _start_mem(nullptr), _usertype(usertype)
    {
        // ftok获取_key  原型：key_t ftok(const char *pathname, int proj_id);
        _key = ftok(pathname.c_str(), projid);
        if (_key < 0)
        {
            ERR_EXIT("ftok");
        }
        if (_usertype == CREATER)
            Create();
        else if (_usertype == USER)
            Get();
        else
        {
           //TODO
        }
        Attach();
    }

    int Size()
    {
        return _size;
    }

    void* VirtualAddr()
    {
        printf("VirtualAddr: %p\n", _start_mem);
        return _start_mem;
    }

    void Attribute()
    {
        struct shmid_ds ds;
        int n = shmctl(_shmid, IPC_STAT, &ds); //ds是输出型参数用于设置属性
        printf("shm_segsz: %ld\n", ds.shm_segsz);
        printf("key:0x%x\n", ds.shm_perm.__key);
    }

    ~Shm()
    {
        std::cout << _usertype << std::endl;
    }

private:
    int _shmid;
    key_t _key;
    int _size;
    void *_start_mem;
    std::string _usertype;
};